import { createI18n } from 'vue-i18n'
import { I18nPlatformClient } from './platform-client'
import { fallbackConfig, platformConfig } from '../config/index'

const platformClient = new I18nPlatformClient(platformConfig)

const i18n = createI18n({
  legacy: false,
  locale: platformConfig.defaultLocale,
  fallbackLocale: platformConfig.fallbackLocale,
  messages: {},
  globalInjection: true,
  missingWarn: false,
  fallbackWarn: false
})

/**
 * 加载指定语言的词条
 * @param {string} locale - 语言代码
 * @returns {Promise<{success: boolean, count?: number, error?: string}>}
 */
async function loadTranslations(locale) {
  try {
    const messages = await platformClient.fetchTranslations(locale)
    console.log('messages', messages)
    i18n.global.setLocaleMessage(locale, {
        ...messages
    })
    
    console.log(`✓ 词条已加载: ${locale}`, { keysCount: Object.keys(messages).length })
    return { success: true, count: Object.keys(messages).length }
  } catch (error) {
    console.error(`加载词条失败 (${locale}):`, error)
    
    if (!i18n.global.availableLocales.includes(locale)) {
      i18n.global.setLocaleMessage(locale, fallbackConfig[locale] || {})
    }
    
    return { success: false, error: error.message }
  }
}

let initialized = false
let initPromise = null

/**
 * 初始化 i18n，加载默认语言词条
 * @returns {Promise<{success: boolean, count?: number, error?: string}>}
 */
export async function initI18n() {
  if (initialized) return { success: true }
  if (initPromise) return initPromise
  
  initPromise = (async () => {
    initialized = true
    const result = await loadTranslations(platformConfig.defaultLocale)
    if (!result.success) {
      console.error('❌ 应用启动时词条加载失败')
    }
    return result
  })()
  
  return initPromise
}

/**
 * 切换语言或刷新词条
 * @param {string} locale - 目标语言代码
 * @throws {Error} 如果词条加载失败
 */
export async function switchLocale(locale) {  
  
    const result = await loadTranslations(locale)
    if (!result.success) {
      console.warn(`语言 ${locale} 加载失败`, result.error)
      throw new Error(result.error || `Failed to load locale: ${locale}`)
    }
  
  i18n.global.locale.value = locale
  
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem('i18n-locale', locale)
  }
}


/**
 * 从本地存储恢复语言设置
 */
if (typeof localStorage !== 'undefined') {
  const savedLocale = localStorage.getItem('i18n-locale')
  if (savedLocale && savedLocale !== platformConfig.defaultLocale) {
    setTimeout(() => {
      switchLocale(savedLocale).catch(err => {
        console.warn('恢复语言设置失败', err)
      })
    }, 100)
  }
}
/**
 * 监听刷新事件
 */
if (typeof window !== 'undefined') {
  window.addEventListener('i18n-refresh', () => {
    const currentLocale = i18n.global.locale.value
    loadTranslations(currentLocale)
  })
}

export default i18n
